<template>
	<!-- 需续费合同 -->
	<div class="app-container">
		<!-- 使用搜索组件 -->
		<searchOption id="searchForm" ref="searchUnit" type="contract" :total="total" :status="queryParams.status"
			:taskType="queryParams.taskType" @searchList="parentSearchList"></searchOption>

		<vxe-table border ref="xTable" size="mini" show-overflow :data="infoList" :column-config="{ resizable: false }"
			:cell-style="cellStyle" :edit-config="{ trigger: 'click', mode: 'cell' }" @scroll="srcollFn"
			:height="autoTableHeight">
			<vxe-column field="firstSignDate" title="首次签约时间" width="125">
				<template #default="{ row }">
					{{ row.firstSignDate }}
				</template>
			</vxe-column>

			<vxe-column field="cooperationYears" title="合作年限" width="70">
				<template #default="{ row }">
					{{ formatDate(row) }}
				</template>
			</vxe-column>

			<vxe-column field="customManager" title="销售经理" width="80">
				<template #default="{ row }">
					{{ row.customManager }}
				</template>
			</vxe-column>

			<vxe-column field="customName" title="公司名称" width="230">
				<template #default="{ row }">
					{{ row.customName }}
				</template>
			</vxe-column>

			<vxe-column field="oldAccounts" title="合同类型" width="70">
				<template #default="{ row }">
					{{ formatOldAccounts(row) }}
				</template>
			</vxe-column>

			<vxe-column field="callName" title="合同图片" width="70">
				<template #default="{ row }">
					<el-button @click="showPdfDialog(row)" type="text">查看合同</el-button>
				</template>
			</vxe-column>

			<vxe-column field="" title="服务项目" width="70">
				<template #default="{ row }">
					<el-popover placement="bottom" width="50%" title="服务项目" trigger="hover" content="111111"
						transition="fade-in-linear" @show="showServiceItems(row.id)">
						<span slot="reference" style="color: #1890ff;">服务项目</span>
						<div style="padding: 0px;">
							<span style="white-space: pre-line" v-html="ServiceItemText"></span>
						</div>
					</el-popover>
				</template>
			</vxe-column>

			<vxe-column field="diffDays" title="合同结束/天" width="75">
				<template #default="{ row }">
					{{ row.diffDays }}
				</template>
			</vxe-column>

			<vxe-column field="callName" title="法人姓名" width="70">
				<template #default="{ row }">
					{{ row.callName }}
				</template>
			</vxe-column>

			<vxe-column field="callPhone" title="联系电话" width="100">
				<template #default="{ row }">
					{{ row.callPhone }}
				</template>
			</vxe-column>

			<vxe-column field="gmtCreate" title="签约时间" width="125">
				<template #default="{ row }">
					{{ row.gmtCreate }}
				</template>
			</vxe-column>

			<vxe-column field="renewalDate" title="续费日期" width="125">
				<template #default="{ row }">
					{{ row.renewalDate }}
				</template>
			</vxe-column>

			<vxe-column field="entrustCycleStrat" title="服务开始日期" width="90">
				<template #default="{ row }">
					<span>{{ parseTime(row.entrustCycleStrat, "{y}-{m}-{d}") }}</span>
				</template>
			</vxe-column>

			<vxe-column field="entrustCycleEnd" title="服务结束日期" width="90">
				<template #default="{ row }">
					<span>{{ parseTime(row.entrustCycleEnd, "{y}-{m}-{d}") }}</span>
				</template>
			</vxe-column>
			<vxe-column field="contractAmount" title="合同金额" width="120">
				<template #default="{ row }">
					{{ row.contractAmount }}
				</template>
			</vxe-column>

			<vxe-column title="操作" width="180">
				<template #default="{ row }">
					<el-button size="mini" type="text" icon="el-icon-edit" @click="createRenewContract(row, 1)">修改合同</el-button>
					<el-button size="mini" type="text" icon="el-icon-view" @click="createRenewContract(row, 2)">生成续费合同</el-button>
				</template>
			</vxe-column>
		</vxe-table>

		<!-- 生成续费合同 -->
		<el-dialog title="续费生成合同" :visible.sync="openRenewContract" width="60%" append-to-body
			:close-on-click-modal="false">
			<contract-dia ref="contractDiaRef" @closeDialog="cancelRenewContract" :rowObj="rowObj"></contract-dia>
		</el-dialog>
		<!-- 查看合同 -->
		<el-dialog :visible.sync="pdfDialog.show" title="查看合同">
			<div class="dialog-wrap">
				<div class="item-title">{{ pdfDialog.title }}</div>
				<div class="item-content-wrap">
					<el-scrollbar>
						<div class="item-content">
							<div class="pdf" id="pdfView"></div>
						</div>
					</el-scrollbar>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import {
	listInfo,
	getInfo,
	delInfo,
	addInfo,
	updateInfo,
	listForDue,
	openPDF,
	serviceItems,
} from "@/api/contract/info";
import { addStep } from "@/api/system/step";
import { addTask } from "@/api/system/task";
import moment from "moment";
import ContractDia from "@/components/ContractDia";
import Pdfh5 from "pdfh5";
import "pdfh5/css/pdfh5.css";
import searchOption from "@/components/searchOption";

export default {
	components: {
		ContractDia,
		searchOption
	},
	name: "Info",
	dicts: [],
	data() {
		return {
			requeryFlag: true,
			// 服务项目明细
			ServiceItemText: '',
			autoTableHeight: 750,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 【请填写功能名称】表格数据
			infoList: [],
			// 弹出层标题
			title: "回款金额",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 30,
				taskType: -1,
				callName: null,
				callPhone: null,
				customName: null,
				customManager: null,
				contractStatus: null,
				entrustCycleStrat: null,
				entrustCycleEnd: null,
				alldata: null,//1表示所有数据，0表示到期数据
			},
			// 表单校验
			rules: {},
			openRenewContract: false,
			//当前dia 行数据
			rowObj: {},
			pdfDialog: {
				show: false,
				title: "",
			},
			pdfh5: null,
		};
	},
	created() {
		// this.getList();
	},
	watch: {
		// 监听路由对象中的变化
		'$route': {
			handler: function (from, to) {
				// 当路由发生变化时会调用这个函数
				this.infoList = [];
				this.queryParams.pageNum = 1;
				this.queryParams.pageSize = 30;
				this.queryParams.customName = null;
				this.queryParams.callPhone = null;
				this.queryParams.callName = null;
				this.queryParams.customManager = null;
				this.queryParams.taskType = -1;
				this.queryParams.taskType_copy = -1;
				this.queryParams.contractType = from.query.contractType;
				this.queryParams.contractStatus = from.query.contractStatus;
				this.queryParams.allData = from.query.allData;
				this.getList();
				this.$nextTick(() => {
					if (from.query.contractStatus == 3) {
						this.$refs.searchUnit.hide = true;
					} else {
						this.$refs.searchUnit.hide = false;
					}
				})
			},
			// 如果需要在路由变化时立即响应，可以设置immediate为true
			immediate: true
		}
	},
	mounted() {
		this.$nextTick(() => {
			// 视口高度 - 列表上方的元素高度
			let allHeight = window.innerHeight;
			let element = [
				document.getElementById('navbar'),
				document.getElementById('searchForm'),
				document.getElementById('tags-view-container'),
			]
			let domHeight = element.map(item => item.offsetHeight)
			// let tableHeight = allHeight - 50 - 34 - 50 - 36;
			let tableHeight = allHeight - 40 - domHeight[0] - domHeight[1] - domHeight[2];
			this.autoTableHeight = tableHeight;
		})
	},
	methods: {
		// 搜索子组件触发搜索
		parentSearchList(data) {
			this.queryParams.pageNum = data.pageNum;
			this.queryParams.pageSize = data.pageSize;
			this.queryParams.callName = data.callName;
			this.queryParams.callPhone = data.callPhone;
			this.queryParams.taskType = data.taskType !== null && data.taskType !== '' ?
				data.taskType : data.taskTypeFlag ? this.queryParams.taskType_copy : this.queryParams.taskType;
			this.queryParams.customName = data.customName;
			this.queryParams.customManager = data.customManager;
			this.queryParams.entrustCycleStrat = data.timeFrame == null ? null : data.timeFrame[0];
			this.queryParams.entrustCycleEnd = data.timeFrame == null ? null : data.timeFrame[1];
			this.handleQuery();
		},
		/** 查询【请填写功能名称】列表 */
		getList() {
			this.loading = true;
			listForDue(this.queryParams).then((response) => {
				response.rows.forEach(element => {
					element.cooperationYears = '';
				});
				this.infoList = response.rows;
				this.total = response.total;
				this.loading = false;
			});
		},
		// 列背景颜色
		cellStyle({ row, column }) {
			if (column.field === "customName") {
				if (row.diffDays < 90) {//|| row.degree == 1
					return {
						backgroundColor: "#FF9192 !important",
					};
				}
			}
		},
		// 表单重置
		reset() {
			this.resetForm("form");
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm");
			this.handleQuery();
		},
		//生成续费合同
		createRenewContract(row, type) {
			this.openRenewContract = true;
			// row.id = null;
			this.rowObj = row;
			if (type == 2) {
				this.rowObj.renew = true;//生成续费合同的标识
			} else {
				this.rowObj.isNew = true;
			}
			this.$nextTick(() => {
				this.$refs.contractDiaRef.reset();
			});
		},
		// 查看服务项目
		showServiceItems(id) {
			this.ServiceItemText = '';
			serviceItems(id).then((response) => {
				this.ServiceItemText = response.data.amountOrRemind;
			})
		},
		//关闭续费合同dia
		cancelRenewContract() {
			this.openRenewContract = false;
			this.$refs.contractDiaRef.reset();
			this.getList();
		},
		// 滚动加载
		srcollFn(e) {
			let circulateNum = this.total / 30;
			let bottomOffset = e.scrollHeight - e.scrollTop - e.bodyHeight;
			if (bottomOffset < 50 && this.queryParams.pageNum < circulateNum) {
				if (this.requeryFlag) {
					this.loading = true;
					this.requeryFlag = false;
					this.queryParams.pageNum++;
					const h = this.$createElement;
					listForDue(this.queryParams).then((response) => {
						response.rows.forEach(element => {
							element.cooperationYears = '';
						});
						this.infoList = [...this.infoList, ...response.rows];
						this.loading = false;
						this.requeryFlag = true;
					});
				}
			}
		},
		// 查看合同
		showPdfDialog(item) {
			this.pdfDialog.show = true;
			openPDF(item.contractCode).then((response) => {
				let blob = response;
				let blobURL = window.URL.createObjectURL(blob);
				this.pdfh5 = new Pdfh5("#pdfView", {
					pdfurl: blobURL,
				});
			});
		},
		// 合同类型 新注册 或 老账新接
		formatOldAccounts(row) {
			if (row.oldAccounts && row.oldAccounts == 1) {
				return '老账新接'
			} else {
				return '新注册'
			}
		},
		// 合作年限，当前年月日-首次签约日期row.firstSignDate  返回格式为 x年x月
		formatDate(row) {
			if (row.firstSignDate == null) {
				return ''
			}
			const currentDate = new Date();
			const year = currentDate.getFullYear();
			const month = ((currentDate.getMonth() + 1) < 10) ? '0' + (currentDate.getMonth() + 1) : currentDate.getMonth() + 1; // 月份从0开始，需要加1
			const day = (currentDate.getDate() < 10) ? '0' + currentDate.getDate() : currentDate.getDate();
			const nowDate = `${year}-${month}-${day}`;
			const diff = new Date(nowDate).getTime() - new Date(row.firstSignDate).getTime();
			const allMonths = Math.floor(diff / 1000 / 60 / 60 / 24 / 30);
			const diffYear = Math.floor(allMonths / 12);
			const diffMonth = Math.floor(allMonths % 12);
			// const diffDay = diff / 1000 / 60 / 60 / 24;
			let string = '';
			if (diffYear > 0) {
				string = `${diffYear}年${diffMonth}个月`;
			} else {
				string = `${diffMonth <= 0 ? 1 : diffMonth}个月`;
			}
			return string;
		}
	},
};
</script>